package o2o.web.actions.order.policy;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPolicyRecordMemory;
import o2o.cache.sys.SysVariablePaotuiMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.ORDER_STATUS;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.policy.INSURANCE_STATUS;
import o2o.dao.PO.policy.PolicyInfo;
import o2o.dao.PO.sys.SYS_VARIABLE_PAOTUI;
import o2o.dao.PO.sys.SysVariablePaotui;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.policy.PolicyInfoVO;
import o2o.service.order.other.OtherOrderService;
import o2o.web.actions.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 保险列表
 */
@RestController
public class OrderPolicyAction {


    @Autowired
    private OtherOrderService otherOrderService;

    // 管理员查看保险信息
    @RequestMapping(value = "/admin/order/policy/record/list")
    public String order_policy_record_by_orderno(String token, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有操作权限");
        }
        List<PolicyInfoVO> policyInfoVOList = this.listOfOrderNo(orderNo);
        return AjaxResult.successResult(policyInfoVOList.size(), policyInfoVOList);
    }

    // 获取
    @RequestMapping(value = "/user/order/policy/record/list")
    public String user_order_policy_record_by_orderno(String token, String orderNo) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        OrderInfo info = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (info == null) {
            return AjaxResult.errorResult("未获取到订单信息");
        }
        if (!user.getUsername().equals(info.getUsername())) {
            return AjaxResult.errorResult("此订单不属于您");
        }
        List<PolicyInfoVO> policyInfoVOList = this.listOfOrderNo(orderNo);
        return AjaxResult.successResult(policyInfoVOList.size(), policyInfoVOList);
    }

    /**
     * 用户保险重新发送
     *
     * @param token
     * @param policyId
     * @param info
     * @return
     */
    @RequestMapping(value = "/user/order/policy/record/send/again")
    public String user_order_policy_record_modify(String token, Long policyId, PolicyInfo info) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(info.getOrderNo());
        if (orderInfo == null) {
            return AjaxResult.errorResult("未获取到订单信息");
        }
        if (ORDER_STATUS.userOrderCancelSet.contains(orderInfo.getOrderStatus()) || (orderInfo.getIsPaid() == null || orderInfo.getIsPaid() == 0)) {
            return AjaxResult.errorResult("当前订单下不可操作");
        }
        PolicyInfo policyInfo_db = OrderPolicyRecordMemory.getInstance().getById(policyId);
        if (policyInfo_db == null) {
            return AjaxResult.errorResult("未获取到信息");
        }
        if ((policyInfo_db.getStatus() != INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_FAIL
                && policyInfo_db.getStatus() != INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_EXIST_ERR) || policyInfo_db.getIsCancel() == 1) {
            return AjaxResult.errorResult("当前状态下不可操作");
        }

        // 获取保险代码
        SysVariablePaotui byCode = SysVariablePaotuiMemory.getInstance().getByCode(SYS_VARIABLE_PAOTUI.BAO_XIAN);
        if (byCode == null) {
            return AjaxResult.errorResult("未获取到保险信息");
        }
        if (ValidateUtil.isNotNull(byCode.getExtra1())) {
            info.setOrderMobile(byCode.getExtra1());
            info.setMobile(byCode.getExtra1());
        }
        StringBuffer sql = new StringBuffer();
        sql.append(" update ").append(PojoTables.ORDER_POLICY_RECORD).append(" SET ")
                .append(" updateUser ='").append(user.getUsername()).append("' ");
        if (ValidateUtil.isNotNull(info.getOrderCardNum())) {
            sql.append(" , orderCardNum ='").append(info.getOrderCardNum()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getOrderMobile())) {
            sql.append(" , orderMobile ='").append(info.getOrderMobile()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getOrderName())) {
            sql.append(" , orderName ='").append(info.getOrderName()).append("' ");
        }
        if (info.getRelation() != null) {
            sql.append(" , relation = ").append(info.getRelation()).append(" ");
        }
        if (ValidateUtil.isNotNull(info.getName())) {
            sql.append(" , name ='").append(info.getName()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getMobile())) {
            sql.append(" , mobile ='").append(info.getMobile()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getCardNum())) {
            sql.append(" , cardNum ='").append(info.getCardNum()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getBeginDate())) {
            sql.append(" , beginDate ='").append(info.getBeginDate()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getEndDate())) {
            sql.append(" , endDate ='").append(info.getEndDate()).append("' ");
        }
        if (ValidateUtil.isNotNull(info.getBirthDay())) {
            sql.append(" , birthDay ='").append(info.getBirthDay()).append("' ");
        }
        sql.append(", status =").append(INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_SELF_UNDEAL)
                .append(", reason = '' ");
        sql.append(" where delFlag = 0 and id = ").append(policyId);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderPolicyRecordMemory.getInstance().addOrModify(orderInfo.getOrderNo());
        // 发送给第三方
        PolicyInfo policyInfo = OrderPolicyRecordMemory.getInstance().getById(policyId);
        if (policyInfo.getStatus() == INSURANCE_STATUS.THREAD_ORDER_INSURANCE_STATUS.INSURANCE_DEALING) {
            List<PolicyInfo> list = new ArrayList<>();
            list.add(policyInfo);
            otherOrderService.sendThreadPolicy(list, orderInfo.getOrderNo(), user.getUsername());
        }
        return AjaxResult.successResult();
    }


    /**
     * 查询订单的保单信息
     *
     * @param orderNo
     * @return
     */
    public List<PolicyInfoVO> listOfOrderNo(String orderNo) {
//        String sql = "select * from " + PojoTables.ORDER_POLICY_RECORD + " where delFlag = 0 and orderNo ='" + orderNo + "'";
//        List<PolicyInfoVO> policyInfoList = null;
//        try {
//            policyInfoList = (List<PolicyInfoVO>) UserDaoSql.getInstance().list(PolicyInfoVO.class, sql);
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        return ValidateUtil.isAbsList(policyInfoList) ? policyInfoList : Collections.emptyList();
        List<PolicyInfo> infoList = OrderPolicyRecordMemory.getInstance().listOfOrderNo(orderNo);
        if (!ValidateUtil.isAbsList(infoList)) {
            return Collections.emptyList();
        }
        return infoList.stream().map(item -> {
            PolicyInfoVO vo = new PolicyInfoVO();
            BeanUtils.copyProperties(item, vo);
            return vo;
        }).collect(Collectors.toList());
    }
}
